/*
 * Copyright (c) 2024 坚果派
 * 
 * 公众号：nutpi
 * 电话：17752170152
 * 官网：https://www.nutpi.net/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_digital_timer_depo/models/countdown_timer.dart';
import 'package:flutter_digital_timer_depo/models/time_format.dart';

class CountdownDisplay extends StatefulWidget {
  final CountdownTimer countdownTimer;
  final TimeFormat timeFormat;
  final double fontSize;
  final Color textColor;
  final VoidCallback? onComplete;

  const CountdownDisplay({
    Key? key,
    required this.countdownTimer,
    this.timeFormat = TimeFormat.arabic,
    this.fontSize = 48.0,
    this.textColor = Colors.black,
    this.onComplete,
  }) : super(key: key);

  @override
  State<CountdownDisplay> createState() => _CountdownDisplayState();
}

class _CountdownDisplayState extends State<CountdownDisplay> {
  late Timer _timer;
  late Duration _remainingTime;
  bool _isCompleted = false;

  @override
  void initState() {
    super.initState();
    _remainingTime = widget.countdownTimer.remainingTime;
    _startTimer();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _remainingTime = widget.countdownTimer.remainingTime;
        
        if (_remainingTime.inSeconds <= 0 && !_isCompleted) {
          _isCompleted = true;
          if (widget.onComplete != null) {
            widget.onComplete!();
          }
        }
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  String _formatDurationArabic(Duration duration) {
    final hours = duration.inHours.toString().padLeft(2, '0');
    final minutes = (duration.inMinutes % 60).toString().padLeft(2, '0');
    final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
    
    return '$hours:$minutes:$seconds';
  }

  String _formatDurationChinese(Duration duration) {
    final chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十',
                       '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九',
                       '二十', '二十一', '二十二', '二十三', '二十四'];
    
    String formatNumber(int number) {
      if (number < 25) {
        return chineseNums[number];
      } else {
        return number.toString(); // 超出范围时使用阿拉伯数字
      }
    }
    
    final hours = duration.inHours;
    final minutes = duration.inMinutes % 60;
    final seconds = duration.inSeconds % 60;
    
    return '${formatNumber(hours)}时${formatNumber(minutes)}分${formatNumber(seconds)}秒';
  }

  String _formatProgress() {
    final total = widget.countdownTimer.endTime.difference(widget.countdownTimer.startTime);
    final elapsed = DateTime.now().difference(widget.countdownTimer.startTime);
    final progress = (elapsed.inSeconds / total.inSeconds * 100).clamp(0, 100).toStringAsFixed(1);
    return '$progress%';
  }

  @override
  Widget build(BuildContext context) {
    final timeString = widget.timeFormat == TimeFormat.arabic
        ? _formatDurationArabic(_remainingTime)
        : _formatDurationChinese(_remainingTime);

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (widget.countdownTimer.label.isNotEmpty)
          Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: Text(
              widget.countdownTimer.label,
              style: TextStyle(
                fontSize: widget.fontSize * 0.5,
                color: widget.textColor,
              ),
            ),
          ),
        Text(
          timeString,
          style: TextStyle(
            fontSize: widget.fontSize,
            color: widget.textColor,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          '从 ${widget.countdownTimer.startTime.toString().substring(11, 19)} 开始',
          style: TextStyle(
            fontSize: widget.fontSize * 0.4,
            color: widget.textColor.withOpacity(0.7),
          ),
        ),
        Text(
          '到 ${widget.countdownTimer.endTime.toString().substring(11, 19)} 结束',
          style: TextStyle(
            fontSize: widget.fontSize * 0.4,
            color: widget.textColor.withOpacity(0.7),
          ),
        ),
        const SizedBox(height: 4),
        Text(
          _formatProgress(),
          style: TextStyle(
            fontSize: widget.fontSize * 0.6,
            color: widget.textColor,
          ),
        ),
      ],
    );
  }
}